package cn.edu.henu.team.fragments;

import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.Rotate;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import androidx.appcompat.app.AlertDialog;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.base.BaseFragment;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.ui.MessageAlertActivity;
import cn.edu.henu.team.ui_login.LoginActivity;
import cn.edu.henu.team.ui.AboutActivity;
import cn.edu.henu.team.ui.AddPostingActivity;
import cn.edu.henu.team.ui.FocusListActivity;
import cn.edu.henu.team.ui.FollowersListActivity;
import cn.edu.henu.team.ui.LikeActivity;
import cn.edu.henu.team.ui.MyCollectionActivity;
import cn.edu.henu.team.ui.MyFocusActivity;
import cn.edu.henu.team.ui.MyPostingActivity;
import cn.edu.henu.team.ui.UserMessageActivity;
import cn.edu.henu.team.utils.LocationUtils;
import de.hdodenhof.circleimageview.CircleImageView;

import static cn.bmob.v3.Bmob.getApplicationContext;

public class fragment4 extends BaseFragment {
    private fragment4 mContext;
    @BindView(R.id.headView)
    CircleImageView headView;
    @BindView(R.id.bgView)
    ImageView bgView;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.brief_intro)
    TextView brief_intro;
    @BindView(R.id.focus)
    TextView focus;
    @BindView(R.id.focusId_sum)
    TextView focusId_sum;
    @BindView(R.id.followers)
    TextView followers;
    @BindView(R.id.follower_sum)
    TextView follower_sum;
    @BindView(R.id.fab)
    FloatingActionButton fab;

    private ListView listView;
    private String now_user_img_url;
    private String followeList_id;//当前用户对应的粉丝user_followers的object

    private String addressMsg;
    private double Latitude, Longitude;

    private List<Map<String, Object>> data = new ArrayList<>();
    private SimpleAdapter simpleAdapter;

    public static fragment4 newInstance() {
        fragment4 fragment = new fragment4();
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_4;
    }

    @Override
    protected void initView() {
        mContext = fragment4.this;

        listView = mRootView.findViewById(R.id.listview);
        listView.addHeaderView(new ViewStub(getApplicationContext()));
        listView.addFooterView(new ViewStub(getApplicationContext()));
    }

    @Override
    protected void initData() {
        //初始化列表
        Integer[] images = {R.drawable.ic_account, R.drawable.ic_blog, R.drawable.ic_focus, R.drawable.ic_collect,
                R.drawable.ic_favorite, R.drawable.ic_announcement, R.drawable.ic_about, R.drawable.ic_out};
        String[] message = {"账号资料", "我的帖子", "我的关注", "我的收藏夹", "我的喜欢", "消息提示", "关于我们", "退出登录"};
        Integer[] icons = {R.drawable.ic_keyboard_arrow_right_24dp, R.drawable.ic_keyboard_arrow_right_24dp, R.drawable.ic_keyboard_arrow_right_24dp, R.drawable.ic_keyboard_arrow_right_24dp, R.drawable.ic_keyboard_arrow_right_24dp,
                R.drawable.ic_keyboard_arrow_right_24dp, R.drawable.ic_keyboard_arrow_right_24dp, R.drawable.ic_keyboard_arrow_right_24dp};
        for (int i = 0; i < 8; i++) {
            Map<String, Object> temp = new LinkedHashMap<>();
            temp.put("image", images[i]);
            temp.put("message", message[i]);
            temp.put("icon", icons[i]);
            data.add(temp);
        }
        simpleAdapter = new SimpleAdapter(getApplicationContext(), data, R.layout.fragment_4_item, new String[]{"image", "message", "icon"}, new int[]{R.id.image, R.id.message, R.id.icon});
        listView.setAdapter(simpleAdapter);
        setListViewHeightBasedOnChildren();


        _User current_user = BmobUser.getCurrentUser(_User.class);
        BmobFile now_user_img = current_user.getHeadPortrait();
        now_user_img_url = now_user_img.getFileUrl();
        //加载网络图片
        Glide.with(getActivity()).load(now_user_img_url).transform(new Rotate(0)).into(headView);
        if (current_user.getCoverPage() != null) {
            Glide.with(getActivity()).load(current_user.getCoverPage().getFileUrl()).into(bgView);
        }
        name.setText(current_user.getNickName().toString());
        if (current_user.getBrief_intro() == null || current_user.getBrief_intro().equals("")) {
            brief_intro.setText("简介：这个人很懒，什么也没留下...");
        } else
            brief_intro.setText("简介：" + current_user.getBrief_intro());

        followeList_id = current_user.getFollower_id().getObjectId();
        follower_sum.setText(Integer.toString(current_user.getFollower_id().getFollower_sum()));
        findFollower_sum();

        //查询关注人数
        BmobQuery<_User> query = new BmobQuery<_User>();
        // focusId是_User表中的字段，用来存储一个用户所关注的对象
        query.addWhereRelatedTo("focusId", new BmobPointer(current_user));
        query.count(_User.class, new CountListener() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    focusId_sum.setText(Integer.toString(integer));
                } else {
                    //Toast.makeText(getApplicationContext(), "关注人数查询失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void clickEvents() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1:
                        Intent it = new Intent(getActivity(), UserMessageActivity.class);
                        startActivity(it);
                        break;
                    case 2:
                        Intent it2 = new Intent(getActivity(), MyPostingActivity.class);
                        startActivity(it2);
                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), MyFocusActivity.class));
                        break;
                    case 4:
                        Intent it3 = new Intent(getActivity(), MyCollectionActivity.class);
                        startActivity(it3);
                        break;
                    case 5:
                        Intent it4 = new Intent(getActivity(), LikeActivity.class);
                        startActivity(it4);
                        break;
                    case 6:
                        Intent it5 = new Intent(getActivity(), MessageAlertActivity.class);
                        startActivity(it5);
                        break;
                    case 7:
                        startActivity(new Intent(getActivity(), AboutActivity.class));
                        break;
                    case 8:
                        createDialog();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /*
     *设置监听点击事件
     */
    @OnClick({R.id.fab, R.id.focus, R.id.focusId_sum, R.id.followers, R.id.follower_sum})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.fab:
                startActivity(new Intent(getActivity(), AddPostingActivity.class));
                break;
            case R.id.focus:
            case R.id.focusId_sum:
                Intent it = new Intent(getActivity(), FocusListActivity.class);
                it.putExtra("objectId", BmobUser.getCurrentUser(_User.class).getObjectId());
                startActivity(it);
                break;
            case R.id.followers:
            case R.id.follower_sum:
                Intent intent = new Intent(getActivity(), FollowersListActivity.class);
                intent.putExtra("objectId", followeList_id);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    public void createDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setMessage("确定退出登录？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        BmobUser.logOut();
                        Intent it = new Intent(getActivity(), LoginActivity.class);
                        startActivity(it);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        alertDialog.show();
    }

    public void findFollower_sum() {
        _User current_user = BmobUser.getCurrentUser(_User.class);
        BmobQuery<_User> query = new BmobQuery<_User>();
        query.include("follower_id");
        query.getObject(current_user.getObjectId(), new QueryListener<_User>() {
            @Override
            public void done(_User object, BmobException e) {
                if (e == null) {
                    follower_sum.setText(Integer.toString(object.getFollower_id().getFollower_sum()));
                    // 查询是否有未读消息，有则显示红点提示
                    boolean flag_1 = (object.getFollower_id().getMessage_fans_sum() == object.getFollower_id().getMessage_fans_read());
                    boolean flag_2 = (object.getFollower_id().getMessage_sayings_sum() == object.getFollower_id().getMessage_sayings_read());

                    if (!(flag_1 == true && flag_2 == true)) {
                        Map<String, Object> temp = new LinkedHashMap<>();
                        temp.put("image", R.drawable.ic_announcement);
                        temp.put("message", "消息提示");
                        temp.put("icon", R.drawable.ic_message);
                        data.set(5, temp);
                        simpleAdapter.notifyDataSetChanged();
                    } else {
                        Map<String, Object> temp = new LinkedHashMap<>();
                        temp.put("image", R.drawable.ic_announcement);
                        temp.put("message", "消息提示");
                        temp.put("icon", R.drawable.ic_keyboard_arrow_right_24dp);
                        data.set(5, temp);
                        simpleAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    // 动态修改listview高度，使得listview能完全展开
    private void setListViewHeightBasedOnChildren() {
        if (listView == null) {
            return;
        }
        if (simpleAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < simpleAdapter.getCount(); i++) {
            View listItem = simpleAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (simpleAdapter.getCount()));
        listView.setLayoutParams(params);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (BmobUser.isLogin()) {
            _User current_user = BmobUser.getCurrentUser(_User.class);
            String now_user_img_url = current_user.getHeadPortrait().getFileUrl();
            //加载网络图片
            Glide.with(getActivity()).load(now_user_img_url).transform(new Rotate(0)).into(headView);
            if (current_user.getCoverPage() != null) {
                Glide.with(getActivity()).load(current_user.getCoverPage().getFileUrl()).into(bgView);
            }

            name.setText(current_user.getNickName().toString());
            if (current_user.getBrief_intro() == null || current_user.getBrief_intro().equals("")) {
                brief_intro.setText("简介：这个人很懒，什么也没留下...");
            } else
                brief_intro.setText("简介：" + current_user.getBrief_intro());
            findFollower_sum();
        }
    }
}
